import CryptoJS from "crypto-js";
// 引入全局utils
import XEUtils from "xe-utils";
import { useDark, useToggle } from "@vueuse/core";
import router from "../router";
import clipboard from "vue-clipboard3";
import api from "@/api";

const modules = import.meta.glob("/src/views/*/*/*.vue");

const tool = {
  // 主题切换工具
  theme: {
    // 是否为暗黑模式
    isDark: useDark(),
    // 切换暗黑模式
    toggleDark() {
      return useToggle(this.isDark)();
    },
  },

  isEmpty(value) {
    if (value == null || value === "" || typeof value === "undefined") {
      return true;
    } else {
      return false;
    }
  },
  isNotEmpty(val) {
    if (val == null || val === "" || typeof val === "undefined") {
      return false;
    } else {
      return true;
    }
  },

  // 常用JS加解密
  crypto: {
    MD5(data) {
      const SALT = "ZLLOVEZLT@1314!@"; // 盐值
      return CryptoJS.MD5(data + SALT).toString();
    },
    BASE64: {
      encrypt(data) {
        return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data));
      },
    },
  },

  // 格式化工具
  format: {
    /**
     * 将时间戳/date转化成yyyy-MM-dd格式数据
     * @param timestamp
     */
    formatDate(timestamp) {
      return XEUtils.toDateString(timestamp, "yyyy-MM-dd");
    },
    formatDateTime(timestamp) {
      return XEUtils.toDateString(timestamp, "yyyy-MM-dd HH:mm:ss");
    },
    formatTime(timestamp) {
      return XEUtils.toDateString(timestamp, "HH:mm:ss");
    },
    getStartOfDay(date) {
      return XEUtils.toDateString(date, "yyyy-MM-dd 00:00:00");
    },
    getEndOfDay(date) {
      let endOfDay = XEUtils.toDateString(date, "yyyy-MM-dd 23:59:59");
      return endOfDay;
    },
  },

  // 数字字典
  dict: {
    // 查询所有字典并缓存到session
    async cacheDict(dictList) {
      if (dictList == null || dictList.length == 0) {
        let res = await api.dictManagement.dict.queryAll.get();
        if (res.code == "01") {
          let pDictTemp = res.data.filter((e) => tool.isEmpty(e.parentId));
          let pDict = pDictTemp.map((e) => {
            return { code: e.dictCode, name: e.dictName, id: e.dictId };
          });
          tool.session.set("pDict", pDict);
          let cDictTemp = res.data.filter((e) => tool.isNotEmpty(e.parentId));
          let cDict = cDictTemp.map((e) => {
            return { value: e.dictKey, label: e.dictValue, pId: e.parentId };
          });
          tool.session.set("cDict", cDict);
        }
      } else {
        let pDictTemp = dictList.filter((e) => tool.isEmpty(e.parentId));
        let pDict = pDictTemp.map((e) => {
          return { code: e.dictCode, name: e.dictName, id: e.dictId };
        });
        tool.session.set("pDict", pDict);
        let cDictTemp = dictList.filter((e) => tool.isNotEmpty(e.parentId));
        let cDict = cDictTemp.map((e) => {
          return { value: e.dictKey, label: e.dictValue, pId: e.parentId };
        });
        tool.session.set("cDict", cDict);
      }
    },
    getList(code) {
      if (tool.isEmpty(code)) {
        return [];
      }
      // 通过code => id
      let dictArray = JSON.parse(tool.session.get("pDict"));
      let pId = dictArray?.find((e) => e.code === code)?.id;
      if (pId) {
        return JSON.parse(tool.session.get("cDict"))
          ?.filter((e) => e.pId === pId)
          ?.map((f) => {
            return { value: f.value, label: f.label };
          });
      } else {
        return [];
      }
    },
    getLabel(code, str) {
      let arr = tool.dict.getList(code);
      return arr?.find((e) => e.value === str)?.label;
    },
    getValue(code, str) {
      let arr = tool.dict.getList(code);
      return arr?.find((e) => e.label === str)?.value;
    },
  },

  // 权限组织
  org: {
    getRc() {
      let rc = JSON.parse(tool.session.get("rightCompany"));
      rc?.forEach((c) => {
        c.companyCode = c.orgCode;
        c.companyName = c.orgName;
        c.companyId = c.orgId;
      });
      return rc ? rc : [];
    },
    getRd() {
      let rd = JSON.parse(tool.session.get("rightDepartment"));
      rd?.forEach((c) => {
        c.departmentCode = c.orgCode;
        c.departmentName = c.orgName;
        c.departmentId = c.orgId;
      });
      return rd ? rd : [];
    },
  },

  // localStorage 相关方法
  data: {
    set(key, data) {
      return localStorage.setItem(key, JSON.stringify(data));
    },
    get(key) {
      try {
        let value = localStorage.getItem(key);
        if (value) {
          value = JSON.parse(value);
          return value;
        } else {
          return null;
        }
      } catch (error) {
        return null;
      }
    },
    remove(key) {
      return localStorage.removeItem(key);
    },
    clear() {
      return localStorage.clear();
    },
  },

  // sessionStorage 相关方法
  session: {
    set(table, data) {
      const _data = JSON.stringify(data);
      return sessionStorage.setItem(table, _data);
    },
    get(table) {
      let data = sessionStorage.getItem(table);
      if (!data) {
        return null;
      }
      return data;
    },
    remove(table) {
      return sessionStorage.removeItem(table);
    },
    clear() {
      return sessionStorage.clear();
    },
  },

  getHeaders() {
    let headers = {};
    let token = JSON.parse(tool.session.get("token"))
      ? JSON.parse(tool.session.get("token"))
      : "";
    let userCode = JSON.parse(tool.session.get("userInfo"))?.userCode;
    if (token && userCode) {
      // token信息和用户信息都存在
      headers["AUTH-TOKEN"] = token;
      headers["USER-CODE"] = userCode;
    }
    return headers;
  },

  /**
   * 对象赋值
   * @param {赋值来源} from
   * @param {赋值实体} to
   */
  assionValues(from, to) {
    const modelKeys = Object.keys(to);
    for (const key in from) {
      if (modelKeys.includes(key) && to.hasOwnProperty(key)) {
        to[key] = from[key];
      }
    }
  },

  /**
   * 对象清除
   * @param {传入的对象} obj
   */
  clearObject(obj) {
    if (typeof obj === "string") {
      return "";
    } else if (typeof obj === "number") {
      return 0;
    } else if (typeof obj === "boolean") {
      return false;
    } else if (typeof obj === "object") {
      if (Array.isArray(obj)) {
        return obj.map(this.clearObject);
      } else {
        const result = {};
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            result[key] = this.clearObject(obj[key]);
          }
        }
        return result;
      }
    }
    return obj;
  },

  /**
   * 清除空属性
   */
  removeEmptyProperties(obj) {
    for (let key in obj) {
      if (obj[key] === "" || obj[key] === null) {
        delete obj[key];
      }
    }
  },

  /**
   * 循环处理树状菜单
   * @param {菜单列表} menus
   * @param {父级菜单} parent
   */
  dealWithRoute(menus, parent = "Layout") {
    if (!menus || menus.length == 0) {
      return;
    }
    for (let item of menus) {
      // 多级菜单
      if (item.children && item.children.length > 0) {
        router.addRoute(parent, {
          path: item.path,
          name: item.name,
          component: modules[`/${item.url}`],
          mete: item.mate,
        });
        this.dealWithRoute(item.children, item.path.split("/")[1]);
      } else {
        // 一级菜单
        router.addRoute(parent, {
          path: item.path,
          name: item.name,
          component: modules[`/${item.url}`],
          mete: item.mate,
        });
      }
    }
  },

  /**
   * 将字符串复制到剪贴板
   * @param {复制的内容} str
   * @returns
   */
  async copy(str) {
    const { toClipboard } = clipboard();
    try {
      await toClipboard(str);
      return true;
    } catch (error) {
      alert("复制失败");
      return false;
    }
  },

  /**
   * 动态获取静态资源
   *
   */
  getAssetsFile(url) {
    return new URL(`../assets/${url}`, import.meta.url).href;
  },

  /**
   * 更新Element Plus语言包
   * 注意：由于Element Plus的语言包是在应用初始化时设置的，
   * 动态切换需要重新加载页面或使用其他方式
   */
  updateElementPlusLocale(locale) {
    // 保存语言设置到localStorage，页面刷新时会使用新的语言包
    localStorage.setItem('elementPlusLanguage', locale);
    // 由于Element Plus的限制，建议刷新页面以应用新的语言包
    console.log('Element Plus locale updated:', locale);
  },
};

export default tool;
